# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {  # dwc 支付方式，费率，单笔限额：支付宝3.5%（2---999），微信3%（1---5000），qq1.5%（1---3000），京东1.8%（1---5000）。do结算。
    'SYF201804180717': {
        'API_KEY': '0A190E8404123F5B1DD72F6CB8E746A0',
        'des_key': 'Mnu3pgErCGpKcKTiNHIWLSsY',
        'query_gateway': 'http://payquery.637pay.com/api/queryPayResult',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYSzVEudm4OGsfLv0kCcf0XvnIlzDfjuXFnAs6
E2lAqs4PwNvQkJeFMrhUeHAlQYJPYMcQdTUI/+Xvd+8/ZpbeIBij8PWvTEUUyjyQGuOGobsozeVK
Z8MbSCZbwOb2IEAPTdOXd1dQ+54ooQRtjDajR6l4oibSgX2g3uUfpJR87QIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ/JbQb5J158QrKD4bc5zryTuy4J
qxmoseePWpeTqSkIf5Mbf6qMJjRN3DAZdv4ThVvqGG2zwRPLGerdGOGu1iVBhzVef5I0U5gLYOlC
+pNH7WVSRbgBO6LyoumRGh4PL/wx4kR7gTT4KWBUlyuo3Bkq6UkDaxJ2eogcoeh7CT2fAgMBAAEC
gYB+BNdXA5O4IhpcPkT7Q7033u9mHLvzzacZsGbLWuqz8P7kn3BtqoDLCYkZ6kt9kRnBZvwDMRya
prj3EY75FvHOSzWx5na+LRkmz4+cxnmNzKO3CtlqJ4X5UqIIkZjhxMuq+IKDGNarbY2vGMoTR1tp
503vtm8fgzsGSaOpVkpskQJBAMz/zRHM5gAnKb6zcwSM2arwyQWFNsbwUkU5RZmm8Ds7OL0np6Dv
2+Xxdh1PHlaaFbbmC3yJasfyx8YFf98a1IcCQQDHihdiKmA6LgaxAtkZIHQjWeUUaRxtQ4UiqSAp
gayfnyiup9LJ/JTlYR1hxDh7zeG9gSH/M+w6XhSBIwDmmiwpAkBDivCtMb6CRGULsSJvWF0LZmRF
Tlv69gmVR0Z4VrmGOn/6Sst/SihAver1wzCyxffrmCYmtTwafxJ1WzCDeNqXAkEAhhZ98DGZyH71
cC4BxajRYpAeKMEZoTMmXExamInTftBtfjC4rZNWW24PWIuLiWaos7f7KIuzyuU90im7iTtBQQJA
XePTgx3JErq0FjiewPSb7Xa9VuyMPiJwvsOSNhcuSc1TtW2BvsiyFxOxEKCZ9xu3VBUj2yMu2iWY
wJYA2pj0Bg==
-----END ENCRYPTED PRIVATE KEY-----""",
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['pub_key']


def _get_pri_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def rsa_long_encrypt(pub_key_str, msg, length=100):
    """
    单次加密串的长度最大为 (key_size/8)-11
    1024bit的证书用100， 2048bit的证书用 200
    """
    pubobj = RSA.importKey(pub_key_str)
    pubobj = Cipher_pkcs1_v1_5.new(pubobj)
    res = []
    for i in range(0, len(msg), length):
        res.append(pubobj.encrypt(msg[i:i + length]))
    return "".join(res)


def rsa_long_decrypt(priv_key_str, msg, length=128):
    """
    1024bit的证书用128，2048bit证书用256位
    """
    privobj = RSA.importKey(priv_key_str)
    privobj = Cipher_pkcs1_v1_5.new(privobj)
    res = []
    for i in range(0, len(msg), length):
        res.append(privobj.decrypt(msg[i:i + length], 'xyz'))
    return "".join(res)


def _gen_md5_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


# 支付宝地址:http://zfb.637pay.com/api/pay
# 支付宝WAP地址:http://zfbwap.637pay.com/api/pay
# QQ钱包地址:http://qq.637pay.com/api/pay
# QQ_WAP地址:http://qqwap.637pay.com/api/pay
# 京东钱包地址:http://jd.637pay.com/api/pay
# 京东WAP地址：http://jd.637pay.com/api/pay
def _get_pay_gateway(service):
    if service == 'wxpay':
        return 'http://wxwap.637pay.com/api/pay'
    elif service == 'wxh5':
        return 'http://wx.637pay.com/api/pay'
    elif service == 'qq':
        return 'http://qqwap.637pay.com/api/pay'
    elif service == 'alipay':
        return 'http://zfbwap.637pay.com/api/pay'
    else:
        return 'http://jd.637pay.com/api/pay'


def _get_pay_type(service):
    if service == 'wxpay':
        return 'WX_WAP'
    elif service == 'wxh5':
        return 'WX_H5'
    elif service == 'qq':
        return 'QQ_WAP'
    elif service == 'alipay':
        return 'ZFB_WAP'
    else:
        return 'JD'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    third_id = time.strftime('%Y%m%d') + str(pay.id)[-8:]
    data = {
        'version': 'V4.0.0.0',
        'merNo': app_id,
        'subMerNo': app_id,
        'netway': _get_pay_type(service),
        'random': '1234',
        'orderNum': third_id,
        'amount': str(int(pay_amount * 100)),
        'goodsName': str(pay.id),
        'callBackUrl': '{}/pay/api/{}/shanyipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'callBackViewUrl': '{}/pay/api/{}/shanyipay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'charset': 'UTF-8',
    }
    j = json.dumps(data, sort_keys=True, separators=(',', ':'))
    data['sign'] = _gen_md5_sign(j + api_key)
    j_p = json.dumps(data, separators=(',', ':'))
    d = rsa_long_encrypt(_get_pub_key(app_id), j_p, 117)
    b = base64.b64encode(d)
    url = _get_pay_gateway(service)
    _LOGGER.info("shanyipay create  url: %s, data: %s", url, j_p)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(url,
                             data='data=' + urllib.quote(b.encode('utf8')) + '&merchNo=' + app_id + '&version=V4.0.0.0',
                             headers=headers, timeout=10)
    _LOGGER.info("shanyipay create rdp data: %s", response.text)
    rsp_obj = json.loads(response.text)
    order_db.fill_third_id(pay.id, third_id)
    return {'charge_info': rsp_obj['qrcodeUrl']}


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    j = json.dumps(params, sort_keys=True, separators=(',', ':'))
    calculated_sign = _gen_md5_sign(j + key)
    if sign != calculated_sign:
        _LOGGER.info("shanyipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def urlsafe_b64decode(rsp_context):
    rsp_context.replace('-', '+').replace('_', '/')
    mod4 = len(rsp_context) % 4
    if mod4 > 0:
        rsp_context += '===='[mod4:]
    return base64.b64decode(rsp_context)


# 0
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("shanyipay notify data: %s", data)
    _LOGGER.info("shanyipay notify body: %s", request.body)
    data = str(urllib.unquote(data['data']).decode('utf8'))
    _LOGGER.info("shanyipay url decode data: %s", data)

    tmp = urlsafe_b64decode(data)
    tmp = rsa_long_decrypt(_get_pri_key(app_id), tmp)
    data = json.loads(tmp)
    verify_notify_sign(data, api_key)
    pay_id = data['goodsName']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('shanyipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['payResult'])
    trade_no = data['orderNum']
    total_fee = float(data['realAmount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '00':
        _LOGGER.info('shanyipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    api_key = _get_api_key(app_id)
    data = OrderedDict((
        ('merNo', app_id),
        ('netway', _get_pay_type(pay_order.service)),
        ('orderNum', str(pay_order.third_id)),
        ('amount', str(int(pay_order.total_fee * 100))),
        ('goodsName', str(pay_order.id)),
        ('payDate', pay_order.created_at.strftime('%Y-%m-%d')),
    ))
    j = json.dumps(data, sort_keys=True, separators=(',', ':'))
    data['sign'] = _gen_md5_sign(j + api_key)

    j_p = json.dumps(data, separators=(',', ':'))
    d = rsa_long_encrypt(_get_pub_key(app_id), j_p, 117)
    b = base64.b64encode(d)
    url = _get_query_gateway(app_id)
    ss = 'data=' + urllib.quote(b.encode('utf8')) + '&merchNo=' + app_id + '&version=V4.0.0.0'
    _LOGGER.info("shanyipay query  url: %s, data: %s, raw: %s", url, j_p, ss)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=ss, headers=headers, timeout=10)
    _LOGGER.info("shanyipay query rdp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['payStateCode'])
        trade_no = data['orderNum']
        total_fee = float(pay_order.total_fee)

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '00':
            _LOGGER.info('shanyipay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('shanyipay data error, status_code: %s', response.status_code)
